#!/usr/bin/python3
# -*- coding: UTF-8 -*-

from apscheduler.schedulers.background import BackgroundScheduler
import urllib.request
import ssl
import logging

from flask import Flask, request
from flask import render_template

app = Flask(__name__)


@app.route('/', methods=['GET', 'POST'])
def index():
    result = "定时任务"
    return result


@app.route('/enable', methods=['GET'])
def enable():
    createSchedule()
    return "启动定时任务成功"


def task():
    context = ssl._create_unverified_context()
    url = "http://192.168.70.1:9002/test/info"
    request = urllib.request.Request(url)
    response = urllib.request.urlopen(url=request, context=context)
    if response.code == 200:
        logging.info("execute schedule success!")
    else:
        logging.info("execute schedule fail!")


def createSchedule():
    # 创建调度器：BlockingScheduler
    scheduler = BackgroundScheduler()
    # 添加任务scheduleTask
    scheduler.add_job(task, 'cron', second="*/2", minute="*", hour="*", day_of_week="*", day="*", month="*",
                      year="*", id='doJob', timezone="Asia/Shanghai")
    scheduler.start()


if __name__ == '__main__':
    # 创建logger记录器
    logging.basicConfig(format="%(asctime)s %(name)s:%(levelname)s:%(message)s",
                        datefmt="%d-%M-%Y %H:%M:%S", level=logging.DEBUG)

    # app.run()
    # 如果你禁用了debug或信任你所在网络的用户，你可以简单修改调用run()的方法使你的服务器公开可用
    # app.run(host='0.0.0.0')
    app.run(port=9100, debug=False)
